import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import demon_jp from '@/assets/images/Damon_jp.mp4'
import demon_en from '@/assets/images/Damon_en.mp4'
import { getDynamicFonts } from '@/utils/fontUtils';
import { getSubscriptionPath } from '@/utils/userUtils';
import './AiPersonCard.css';
import LoginModal from '@/components/LoginModal';
import { useUserProfile } from '@/hooks/useUserProfile';

// 倒计时 hook - 复用 subscriptions.tsx 的逻辑
function useCountdown(initialMs: number) {
  const [timeLeft, setTimeLeft] = useState(initialMs);
  useEffect(() => {
    if (timeLeft <= 0) return;
    const interval = setInterval(() => {
      setTimeLeft(t => (t > 0 ? t - 100 : 0));
    }, 100);
    return () => clearInterval(interval);
  }, [timeLeft]);
  const hours = Math.floor(timeLeft / 3600000);
  const minutes = Math.floor((timeLeft % 3600000) / 60000);
  const seconds = Math.floor((timeLeft % 60000) / 1000);
  return { hours, minutes, seconds };
}

const PromotionCard: React.FC = () => {
  const navigate = useNavigate();
  const { t, i18n } = useTranslation();
  const dynamicFonts = getDynamicFonts(i18n);
  const countdown = useCountdown(30 * 60 * 1000); // 30分钟
  
  // 根据当前语言选择视频
  const videoSrc = i18n.language === 'ja' ? demon_jp : demon_en;

  // 新增：hover/active状态
  const [isActive, setIsActive] = useState(false);

  // 登录相关状态和方法
  const {
    isLoggedIn,
    showLoginModal,
    closeLoginModal,
    openLoginModal,
    handleLoginSuccessAndUpdateTab
  } = useUserProfile();

  // 鼠标事件处理
  const handleMouseEnter = useCallback(() => setIsActive(true), []);
  const handleMouseLeave = useCallback(() => setIsActive(false), []);
  const handleTouchStart = useCallback(() => setIsActive(true), []);
  const handleTouchEnd = useCallback(() => setIsActive(false), []);

  // 检查登录状态并显示登录弹窗（如果未登录）
  const checkLoginAndShowModal = () => {
    if (!isLoggedIn) {
      openLoginModal(false); // false表示默认显示登录界面而非注册界面
      return false;
    }
    return true;
  };

  // 处理点击事件，检查登录状态
  const handleClick = () => {
    if (checkLoginAndShowModal()) {
      navigate(getSubscriptionPath());
    }
  };

  // 登录成功处理
  const handleLoginSuccess = () => {
    handleLoginSuccessAndUpdateTab();
    navigate(getSubscriptionPath());
  };

  return (
    <div className="relative w-full h-full">
      {/* 增加card-container和active样式 */}
      <div
        className={`relative p-[2px] rounded-3xl h-full card-container bg-gradient-to-bl from-[#F76E85] to-[#5505E6] cursor-pointer${isActive ? ' active' : ''}`}
        style={{ aspectRatio: '9/16' }}
        onClick={handleClick}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
        onTouchStart={handleTouchStart}
        onTouchEnd={handleTouchEnd}
      >
        {/* 渐变边框层 */}
        <div
          className="absolute inset-0 rounded-3xl card-border"
          style={{
            background: 'linear-gradient(to right, #ec4899, #a855f7)',
            zIndex: -1,
          }}
        />
        {/* 主内容区域 - 添加card-content类 */}
        <div className="flex flex-col items-center justify-between h-full w-full rounded-3xl py-4 lg:py-6 card-content relative overflow-hidden">
          {/* 视频背景层 */}
          <div className="absolute inset-0 z-0">
            <video 
              src={videoSrc}
              autoPlay 
              loop 
              muted 
              playsInline
              className="w-full h-full object-cover"
            />
          </div>
          
          {/* 倒计时区域 */}
          <div className="flex-0 relative z-10">
            <div style={{ fontFamily: dynamicFonts.font4 }} className="flex justify-center items-center gap-1.5">
              {/* 小时 */}
              <div className="flex flex-col rounded-lg w-[40px] h-[40px] lg:w-[46px] lg:h-[46px] pt-1.5 bg-[rgba(223,113,244,0.10)] backdrop-blur-[10px]">
                <div className="text-center text-xs lg:text-sm leading-tight font-semibold text-white">
                  {String(countdown.hours).padStart(2, '1')}
                </div>
                <div className="text-center text-xs leading-tight font-normal text-[rgba(255,255,255,0.34)]">
                  {t('subscription.countdownLabels.hrs', { defaultValue: 'Hrs' })}
                </div>
              </div>
              {/* 分钟 */}
              <div className="flex flex-col rounded-lg w-[40px] h-[40px] lg:w-[46px] lg:h-[46px] pt-1.5 bg-[rgba(223,113,244,0.10)] backdrop-blur-[10px]">
                <div className="text-center text-xs lg:text-sm leading-tight font-semibold text-white">
                  {String(countdown.minutes).padStart(2, '0')}
                </div>
                <div className="text-center text-xs leading-tight font-normal text-[rgba(255,255,255,0.34)]">
                  {t('subscription.countdownLabels.min')}
                </div>
              </div>
              {/* 秒钟 */}
              <div className="flex flex-col rounded-lg w-[40px] h-[40px] lg:w-[46px] lg:h-[46px] pt-1.5 bg-[rgba(223,113,244,0.10)] backdrop-blur-[10px]">
                <div className="text-center text-xs lg:text-sm leading-tight font-semibold text-white">
                  {String(countdown.seconds).padStart(2, '0')}
                </div>
                <div className="text-center text-xs leading-tight font-normal text-[rgba(255,255,255,0.34)]">
                  {t('subscription.countdownLabels.sec')}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 登录弹窗 */}
      <LoginModal
        show={showLoginModal}
        onClose={closeLoginModal}
        onLoginSuccess={handleLoginSuccess}
        activeTab="anime_girl"
        initialRegister={false}
      />
    </div>
  );
};

export default PromotionCard; 